#include "timeutils.h"

/**
 * Compare two timespec objects.
 */
int cmp_timespec(const struct timespec &a, const struct timespec &b)
{
    if (a.tv_sec > b.tv_sec)
        return 1;
    else if (a.tv_sec < b.tv_sec)
        return -1;
    else {
        if (a.tv_nsec > b.tv_nsec)
            return 1;
        else if (a.tv_nsec < b.tv_nsec)
            return -1;
        else
            return 0;
    }
}

/**
 * Add certain amount of milliseconds to a timespec object.
 * @param a the timespec object to operate on
 * @param ms the amount of milliseconds
 * @param result the place to store the resulting new timespec object
 */
void add_timespec(const struct timespec &a, int ms, struct timespec *result)
{
    // convert to millisec, add timeout, convert back
    result->tv_sec = a.tv_sec + ms / 1000;
    result->tv_nsec = a.tv_nsec + (ms % 1000) * 1000000;
    while (result->tv_nsec > 1000000000) {
        result->tv_sec++;
        result->tv_nsec -= 1000000000;
    }
}

/**
 * Compute the difference between two timespec objects.
 */
int diff_timespec(const struct timespec &end, const struct timespec &start)
{
    int diff = (end.tv_sec > start.tv_sec)?(end.tv_sec-start.tv_sec)*1000:0;
    if (end.tv_nsec > start.tv_nsec) {
        diff += (end.tv_nsec - start.tv_nsec) / 1000000;
    } else {
        diff -= (start.tv_nsec - end.tv_nsec) / 1000000;
    }
    return diff;
}

